package com.efounder.chat.activity;

import android.app.ProgressDialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import androidx.core.app.ActivityCompat;
import androidx.core.app.ActivityOptionsCompat;
import androidx.appcompat.app.AlertDialog;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.efounder.chat.R;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.http.GetHttpUtil;
import com.efounder.chat.http.OpenEthRequest;
import com.efounder.chat.model.ChatListItem;
import com.efounder.chat.model.MessageEvent;
import com.efounder.chat.struct.StructFactory;
import com.efounder.chat.utils.ChatActivitySkipUtil;
import com.efounder.chat.utils.GroupNameUtil;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.utils.Constants;
import com.efounder.http.EFHttpRequest;
import com.efounder.http.EFHttpRequest.HttpRequestListener;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.util.ToastUtil;
import com.efounder.utils.CommonUtils;
import com.efounder.utils.ResStringUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.LinkedHashMap;
import java.util.Map;

import static com.efounder.frame.utils.Constants.CHAT_PASSWORD;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

/**
 * @author Administrator-lch 用户详情信息  统一到 userinfo
 * @see UserInfoActivity
 */
@Deprecated
public class GroupUserInfoActivity extends BaseActivity {

    // 发送按钮
    private Button btn_sendmsg;
    // 头像区域
    private ImageView iv_avata;
    //空间图标
    private ImageView iv_wode_kj;
    // 性别
    ImageView iv_sex;
    private ImageView iv_detail;
    // 用户名
    private TextView tv_name;
    private TextView tv_zhanghao;
    private TextView tv_nickname;
    private LinearLayout middleArea;

    private byte chatType;
    private int userId;
    private int groupId;
    private String groupRemarkName;
    private String avatar;
    private String zhanghao;
    private User user;
    private boolean isFriend = true;
//    private ImageLoader imageLoader;
//    private DisplayImageOptions options;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_userinfo);
        //initImageLoader();
        userId = getIntent().getIntExtra("id", 1);
        groupId = getIntent().getIntExtra("groupId", 1);
        initView();
        initData();
        initEthUserInfo();
    }

    private void initData() {

        final int loginUserId = Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID));

        user = WeChatDBManager.getInstance().getOneFriendById(userId);
        if (!user.isExist()) {
            isFriend = false;
        }
        user = GroupNameUtil.getGroupUser(groupId, userId);
        groupRemarkName = GroupNameUtil.getGroupUserName(user);
        user.setReMark(groupRemarkName);
        avatar = user.getAvatar();
        chatType = StructFactory.TO_USER_TYPE_PERSONAL;
        zhanghao = user.getName();
        if (zhanghao == null || zhanghao.equals("")) {
            tv_zhanghao.setText(R.string.wrchatview_not_set);

        } else {
            tv_zhanghao.setText(zhanghao);
        }
        tv_nickname.setText(user.getNickName());


        middleArea = (LinearLayout) this.findViewById(R.id.middle_remark);
        iv_detail = (ImageView) findViewById(R.id.iv_detail);
        iv_detail.setVisibility(View.VISIBLE);
        TextView tvTitle = (TextView) this.findViewById(R.id.tv_title);
        tvTitle.setText(R.string.chat_detail_info);
        if (loginUserId == userId) {
            iv_detail.setVisibility(View.INVISIBLE);
        }
        iv_detail.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {

                showPopWindow(iv_detail);

            }
        });
        if (!isFriend) {
            btn_sendmsg.setText(R.string.wrchatview_add_contact_list);
        }
        btn_sendmsg.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (loginUserId == userId) {
                    Toast.makeText(GroupUserInfoActivity.this, ResStringUtil.getString(R.string.chat_not_add_mine_friend), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (isFriend) {
                    EnvironmentVariable.setProperty("currentChatUserId", String.valueOf(userId));
                    Intent intent = new Intent();
                    intent.putExtra("id", userId);
                    intent.putExtra("chattype", StructFactory.TO_USER_TYPE_PERSONAL);

                    ChatActivitySkipUtil.startChatActivity(GroupUserInfoActivity.this, intent);
                    finish();
                } else {
                    searchUser(userId);
                }


            }

        });

        Map<String, String> map = new LinkedHashMap<String, String>();
        String key1 = getResources().getString(R.string.showNumberText);
        map.put(key1, String.valueOf(user.getId()));
        if (EnvironmentVariable.getProperty("isShowWalletAddress", "0").equals("1")) {
            map.put("基地ID", user.getWalletAddress());
        }
        // map.put("手机号码", user.getMobilePhone());
        //map.put("描述:", "");
        if (user.getSigNature() == null || user.getSigNature().equals("")) {
            map.put("个性签名", ResStringUtil.getString(R.string.chat_unfilled));
        } else {
            map.put("个性签名", user.getSigNature());
        }


        user.setRemarkmap(map);

        this.setcontent(user);

    }

    private void initView() {
        btn_sendmsg = (Button) this.findViewById(R.id.btn_sendmsg);
        iv_avata = (ImageView) this.findViewById(R.id.iv_avatar);
        iv_wode_kj = (ImageView) this.findViewById(R.id.iv_wode_kj);
        if (!EnvironmentVariable.getProperty(Constants.KEY_SETTING_APPID).equals("OSPMobileLiveApp")) {
            iv_wode_kj.setVisibility(View.GONE);
        }
        iv_avata.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (user.getAvatar() != null && user.getAvatar().contains("http")) {
                    Intent intent = new Intent(GroupUserInfoActivity.this,
                            ShowBigImageActivity.class);
                    intent.putExtra("path", user.getAvatar());
                    ActivityOptionsCompat options = ActivityOptionsCompat
                            .makeSceneTransitionAnimation(GroupUserInfoActivity.this, iv_avata, "avatar");
                    ActivityCompat.startActivity(GroupUserInfoActivity.this, intent, options.toBundle());
                } else {
                    ToastUtil.showToast(GroupUserInfoActivity.this, R.string.chat_user_not_set_head);
                }
            }
        });
        iv_wode_kj.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isFriend || Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)) == userId) {
                    try {
                        EnvironmentVariable.setProperty("currentChatUserId", String.valueOf(userId));
                        Intent intent = new Intent(GroupUserInfoActivity.this, Class.forName("com.efounder.FriendMZoneActivity"));
                        EnvironmentVariable.setProperty("friendStatusNative", "true");
                        startActivity(intent);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtil.showToast(GroupUserInfoActivity.this, R.string.wrchatview_not_you_friend_please);
                }
            }
        });
        iv_sex = (ImageView) this.findViewById(R.id.iv_sex);
        tv_name = (TextView) this.findViewById(R.id.tv_name);

        tv_zhanghao = (TextView) findViewById(R.id.tv_zhanghao);
        tv_nickname = (TextView) findViewById(R.id.tv_nickname);
    }


    @Override
    protected void onPause() {
        super.onPause();
    }

    private void initEthUserInfo() {
        //显示钱包地址
        if (EnvironmentVariable.getProperty("isShowWalletAddress", "0").equals("1") && user.getWalletAddress() == null) {
            OpenEthRequest.getUserEthByImUserId(GroupUserInfoActivity.this, userId, new OpenEthRequest.EthUserRequestListener() {
                @Override
                public void onSuccess(String ethAddress, String publicKey, String RSAPublicKey) {
//                    user.setWalletAddress(ethAddress);
//                    user.setPublicKey(publicKey);
//                    user.setRSAPublicKey(RSAPublicKey);
//                    weChatDBManager.insertUserTable(user);
//                    initData();
                }
                @Override
                public void onSuccess(User user1) {
                    user.setWalletAddress(user1.getWalletAddress());
                    user.setPublicKey(user1.getPublicKey());
                    user.setRSAPublicKey(user1.getRSAPublicKey());
                    user.setWeixinQrUrl(user1.getWeixinQrUrl());
                    user.setZhifubaoQrUrl(user1.getZhifubaoQrUrl());
                    WeChatDBManager.getInstance().insertUserTable(user);
                    initData();

                }
                @Override
                public void onFail(String error) {

                }
            },true);


        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        user = WeChatDBManager.getInstance().getOneFriendById(userId);
        if (user.getNickName().equals(String.valueOf(userId))) {
            isFriend = false;
            user = WeChatDBManager.getInstance().getOneUserById(userId);
        }
        user = GroupNameUtil.getGroupUser(groupId, userId);
        groupRemarkName = GroupNameUtil.getGroupUserName(user);

        user.setReMark(groupRemarkName);
        // 设置用户名
        tv_name.setText(groupRemarkName);
    }

    /**
     * 设置内容
     *
     * @param user
     */
    private void setcontent(User user) {
        middleArea.removeAllViews();
        // 设置性别
        String sex = user.getSex();

        if ("M".equals(sex)) {
            iv_sex.setImageResource(R.drawable.ic_sex_male);
        } else if ("F".equals(sex)) {
            iv_sex.setImageResource(R.drawable.ic_sex_female);
        } else {
            iv_sex.setVisibility(View.GONE);
        }
        // 设置用户名
        tv_name.setText(groupRemarkName);
        //设置用户头像
//        if (avatar != null && avatar.contains("http")) {
//            imageLoader.displayImage(URLModifyDynamic.getInstance().replace(avatar), iv_avata, options);
//        } else {
//            imageLoader.displayImage("", iv_avata, options);
//        }
        LXGlideImageLoader.getInstance().showUserAvatar(this, iv_avata, avatar);


        // 设置描述区域
        final Map<String, String> remarkMap = user.getRemarkmap();

        LayoutInflater inflater = LayoutInflater.from(this);
        for (final String key : remarkMap.keySet()) {
            System.out.println("key= " + key + " and value= "
                    + remarkMap.get(key));
            ViewGroup userinfo_merge = (ViewGroup) inflater.inflate(
                    R.layout.userinfo_merge, null);
            TextView merge_key = (TextView) userinfo_merge
                    .findViewById(R.id.merge_key);
            merge_key.setText(key);

            TextView merge_value = (TextView) userinfo_merge
                    .findViewById(R.id.merge_value);
            merge_value.setText(remarkMap.get(key));

            ImageView ivCopyAddress = (ImageView) userinfo_merge.findViewById(R.id.iv_copy_address);

            if (key.equals("基地ID")) {
                merge_value.setEllipsize(TextUtils.TruncateAt.MIDDLE);
                merge_value.setMaxLines(1);
                ivCopyAddress.setVisibility(View.VISIBLE);
                ivCopyAddress.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
//                    // 将文本内容放到系统剪贴板里。
                        cm.setText(remarkMap.get(key));
                        ToastUtil.showToast(getApplicationContext(), R.string.chat_copy_to_clipboard);
                    }
                });
            }

            LayoutParams lp = new LayoutParams(
                    LayoutParams.MATCH_PARENT, CommonUtils.dip2px(this, 48));
            middleArea.addView(userinfo_merge, lp);
        }

    }

    @Override
    public void back(View view) {
        Intent intent = getIntent().putExtra("remarkName", groupRemarkName);
        setResult(1, intent);
        finish();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Intent intent = getIntent().putExtra("remarkName", groupRemarkName);
        setResult(1, intent);
        finish();
    }

    private void searchUser(int uid) {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage(ResStringUtil.getString(R.string.chat_adding));
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.show();
        String userid = EnvironmentVariable.getProperty(CHAT_USER_ID);
        String password = EnvironmentVariable.getProperty(CHAT_PASSWORD);
        EFHttpRequest httpRequest = new EFHttpRequest(TAG);
        String url = GetHttpUtil.ROOTURL
                + "/IMServer/user/applyAddFriend?userId=" + userid
                + "&passWord=" + password + "&friendUserId=" + uid;
        httpRequest.httpGet(url);
        httpRequest.setHttpRequestListener(new HttpRequestListener() {

            @Override
            public void onRequestSuccess(int requestCode, String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String info = jsonObject.getString("result");
                    System.out.printf(info);
                    if ("success".equals(info)) {
                        progressDialog.dismiss();
                        user.setState(User.SENT);//好友申请已发送
                        user.setTime(System.currentTimeMillis());
                        user.setIsRead(true);
                        user.setLoginUserId(Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)));
                        WeChatDBManager.getInstance().insertSendNewFriendApply(user);
                        ToastUtil.showToast(GroupUserInfoActivity.this.getApplicationContext(),
                                R.string.chat_send_friend_request_success);
                    } else {
                        progressDialog.dismiss();
                        ToastUtil.showToast(GroupUserInfoActivity.this.getApplicationContext(),
                                R.string.chat_send_friend_request_fail);
                    }
                } catch (JSONException e) {

                    e.printStackTrace();
                }

            }

            @Override
            public void onRequestFail(int requestCode, String message) {


            }
        });
        // WeChatHttpRequest.

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        return super.onKeyDown(keyCode, event);

    }

    public void showPopWindow(View view) {
        final PopupWindow popupWindow = new PopupWindow(this);
        View conentView;
        LayoutInflater inflater = (LayoutInflater) this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        conentView = inflater.inflate(R.layout.popupwindow_beizhu, null);

        RelativeLayout beizhuLayout = (RelativeLayout) conentView.findViewById(R.id.setbeizhi);
        TextView beizhu_title = (TextView) conentView.findViewById(R.id.text1);
        beizhu_title.setText(R.string.chat_set_group_remark);
        RelativeLayout deleteLayout = (RelativeLayout) conentView.findViewById(R.id.deletefriend);
        if (!isFriend) {//如果不是好友 隐藏删除好友的菜单
            deleteLayout.setVisibility(View.GONE);
        }

        beizhuLayout.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(GroupUserInfoActivity.this, UserRemarkActivity.class);
                intent.putExtra("id", userId);
                intent.putExtra("groupId", groupId);
                startActivity(intent);
                popupWindow.dismiss();
            }
        });

        deleteLayout.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
                new AlertDialog.Builder(GroupUserInfoActivity.this).
                        setMessage(ResStringUtil.getString(R.string.chat_sure_delete_friend)).setTitle(ResStringUtil.getString(R.string.wrchatview_prompt)).
                        setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                final ProgressDialog progressDialog = new ProgressDialog(GroupUserInfoActivity.this);
                                progressDialog.setMessage(ResStringUtil.getString(R.string.chat_deleteing));
                                progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                                progressDialog.show();
                                GetHttpUtil.deleteFriend(GroupUserInfoActivity.this, userId, new
                                        GetHttpUtil.UpdateUserInfoCallBack() {


                                            @Override
                                            public void updateSuccess(boolean isSuccess) {
                                                if (isSuccess) {
                                                    progressDialog.dismiss();
                                                    clearBadgem(userId, chatType);

                                                    //跳转到首页
                                                    try {
                                                        String className = getResources().getString(R.string.from_group_backto_first);
                                                        Class clazz = Class.forName(className);
                                                        Intent myIntent = new Intent(GroupUserInfoActivity.this, clazz);
                                                        startActivity(myIntent);
                                                    } catch (ClassNotFoundException e) {
                                                        e.printStackTrace();
                                                    }

                                                    ToastUtil.showToast(GroupUserInfoActivity.this.getApplicationContext(),
                                                            R.string.chat_delete_friend_success);
                                                    Intent intent = getIntent().putExtra("delete", 1);
                                                    setResult(1, intent);
                                                    GroupUserInfoActivity.this.finish();
                                                } else {
                                                    progressDialog.dismiss();
                                                    ToastUtil.showToast(GroupUserInfoActivity.this.getApplicationContext(),
                                                            R.string.chat_delete_friend_fail);
                                                }
                                            }
                                        });
                                dialogInterface.dismiss();
                            }
                        }).show();

            }
        });
        // 设置SelectPicPopupWindow的View
        popupWindow.setContentView(conentView);
        // 设置SelectPicPopupWindow弹出窗体的宽
        popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        // 设置SelectPicPopupWindow弹出窗体的高
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        // 设置SelectPicPopupWindow弹出窗体可点击
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        // 刷新状态
        popupWindow.update();
        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0000000000);
        // 点back键和其他地方使其消失,设置了这个才能触发OnDismisslistener ，设置其他控件变化等操作
        popupWindow.setBackgroundDrawable(dw);

        // 设置SelectPicPopupWindow弹出窗体动画效果
        popupWindow.setAnimationStyle(R.style.AnimationPreview);
        popupWindow.showAsDropDown(view, 0, 0);
    }

    private void clearBadgem(int id, byte chatType) {

        //清除当前聊天的角标
        ChatListItem chatListItem = WeChatDBManager.getInstance().getChatListItem(id, chatType);
        int unReadCount = JFMessageManager.getInstance().
                getUnReadCount(id, chatType);

        JFMessageManager.getInstance().unreadZero(id, chatType);
        if (unReadCount == 0) {
            unReadCount = -1;
        }
        if (chatListItem != null) {
            chatListItem.setBadgernum(unReadCount);
            WeChatDBManager.getInstance().deleteChatListiItem(chatListItem);
            //unReadIntent.putExtra("unReadCount", unReadCount);
            //ChatListItemUtil.updateUnreadCount(unReadCount, 0);
            EventBus.getDefault().post(new MessageEvent(chatListItem, MessageEvent.DELETE));

        }


    }
    /**
     * 异步加载头像
     */
//    public void initImageLoader() {
//        // 初始化异步加载图片的类
//        imageLoader = ImageLoader.getInstance();
//        // 设置异步加载图片的配置信息
//        options = ImageUtil.getImageLoaderOptions(R.drawable.default_useravatar);
//
//    }


}
